package com.leicx.guli.product.exception;

import com.leicx.guli.common.enums.GuliExceptionEnum;
import com.leicx.guli.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author daxiong
 * @date 2021/6/3 9:55 下午
 */
@RestControllerAdvice
@Slf4j
public class GuliExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R parameterCheck(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String, String> collect = fieldErrors.stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        log.error("参数字段校验异常：{}", e.getMessage());
        return R.error(GuliExceptionEnum.PARAMETER_CHECK_ERROR).data(collect);
    }
}
